#!/bin/bash

# 用户名
username='root'
# 密码
pwd='totem@cd'
# 数据库名
dbname='escape'
# 容器名
container='mysql'
# 备份时间
backtime=$(date +%Y%m%d_%H%M%S)
# 备份输出日志路径
logpath='/root/data/mysqlbak'
# 备份文件路径
datapath='/root/data/mysqlbak'

# 修改为你系统中实际的 mysqldump 路径 查看路径命令：find / -name mysqldump 2>/dev/null
mysqldump_path=/usr/local/mysql/bin/mysqldump

echo "################## ${backtime} #############################"
echo "开始备份"
echo "" >> ${logpath}/mysqlback.log
echo "-------------------------------------------------" >> ${logpath}/mysqlback.log
echo "备份时间为 ${backtime}, 备份数据库表 ${dbname} 开始" >> ${logpath}/mysqlback.log

# 使用配置文件进行备份
docker exec ${container} /usr/bin/mysqldump -u ${username} --password=${pwd} ${dbname} > ${datapath}/${dbname}_${backtime}.sql 2>> ${logpath}/mysqlback.log
# 备份成功以下操作
if [ "$?" == 0 ]; then
    cd ${datapath}
    # 为节约硬盘空间，将数据库压缩
    tar zcf ${dbname}_${backtime}.tar.gz ${dbname}_${backtime}.sql > /dev/null
    # 删除原始文件，只留压缩后文件
    rm -f ${datapath}/${dbname}_${backtime}.sql
    # 删除五天前备份，也就是只保存5天内的备份
    find ${datapath} -name "*.tar.gz" -type f -mtime +5 -exec rm -rf {} \; > /dev/null 2>&1
    echo "数据库 ${dbname} 备份成功!!" >> ${logpath}/mysqlback.log
else
    # 备份失败则进行以下操作
    echo "数据库 ${dbname} 备份失败!!" >> ${logpath}/mysqlback.log
fi

echo "完成备份"
echo "################## ${backtime} #############################"